import java.io.BufferedOutputStream;
import java.io.FileOutputStream;
import java.io.ObjectOutput;
import java.io.ObjectOutputStream;
import java.io.OutputStream;

public class RO_ConvertUSERtoITEM {
	static User[] USER = RO_ReadASCII.USER;
	static Item[] ITEM = new Item[624961];
	static String SER_PATH = RO_ReadASCII.FILE_PATH + ".ser";

	public static void go() {
		createItemArrays();
		sortITEM();
		writeSerialisedResult();
	}

	private static void createItemArrays() {
		System.out.println("createItemArrays: " + USER[0]);
		long time = System.currentTimeMillis();

		initItemArray();

		for (int userID = 0; userID < USER.length; userID++) {
			User user = USER[userID];

			for (int v = 0; v < user.ilen; v++) {
				int itemID = user.items[v];
				byte vote = user.votes[v];
				ITEM[itemID].put(userID, vote);
				ITEM[itemID].mean += (double) vote;
			}
		}

		shrinkItems();
		System.out.println(System.currentTimeMillis() - time);
	}

	private static void initItemArray() {
		for (int i = 0; i < ITEM.length; i++) {
			ITEM[i] = new Item();
		}
	}

	private static void shrinkItems() {
		for (int i = 0; i < ITEM.length; i++) {
			ITEM[i].shrink();
		}
	}

	private static void sortITEM() {
		System.out.println("sortITEM: " + USER[0]);
		long time = System.currentTimeMillis();

		for (Item item : ITEM) {
			item.sort();
			item.mean = item.mean / item.ulen;
		}

		System.out.println(System.currentTimeMillis() - time);
	}

	private static void writeSerialisedResult() {
		System.out.println("writeSerialisedResult: " + SER_PATH + ".item");
		long time = System.currentTimeMillis();

		try {
			OutputStream file = new FileOutputStream(SER_PATH + ".item");
			OutputStream buffer = new BufferedOutputStream(file);
			ObjectOutput output = new ObjectOutputStream(buffer);
			try {
				output.writeObject(ITEM);
			} finally {
				output.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		System.out.println(System.currentTimeMillis() - time);
	}
}
